import { install } from 'source-map-support';
install();

import axios from "../node_modules/axios/index.js";
import { Postman } from "./Postman.js"
import { Stat } from "./Stat.js";

const upload = async () => {
    const result = await axios.post<any>('http://builder.fygame.com:3000/api/app/uploadImage', { file: 'D:/robot.png' }, { timeout: 3000 }).catch(() => {});
    console.log(result);
}

Stat.Instance.setJobRoots(['D:/jobs', 'D:/tomcat/webapps/hudson/jobs', 'D:/tomcat/webapps/hudson/jobs.bak']);

const sendMsg = async (chatid: string, year: string, emphasisTitle: string, emphasisDesc: string, subTitle: string) => {
    await Postman.Instance.sendAnyRobotMsg({
        chatid,
        payload: {
            msgtype: "template_card",
            template_card: {
                card_type: "text_notice",
                source: {
                    icon_url: "https://wework.qpic.cn/wwpic3az/876493_6dB6HF5FQXSUi_c_1703846731/0",
                    desc: "我超厉害",
                    desc_color: 0
                },
                main_title: {
                    title: `${year}年度报告`,
                    desc: "来看看这一年来你们这些大聪明都干了啥"
                },
                emphasis_content: {
                    title: emphasisTitle,
                    desc: emphasisDesc
                },
                sub_title_text: subTitle,
                card_action: {
                    type: 1,
                    url: "https://www.jianshu.com/u/406e1c607d50"
                }
            }
        }
    });
}

const formatDuration = (duration: number, needS: boolean) => {
    const h = Math.floor(duration / 3600);
    const m = Math.floor((duration % 3600) / 60);
    let out = `${h}小时${m}分`;
    if (needS) {
        const s = duration % 60;
        out += `${s}秒`
    }
    return out;
}

const formatDate = (yyyymmdd: number) => {
    const month = Math.floor((yyyymmdd % 10000) / 100);
    const day = yyyymmdd % 100;
    return `${month}月${day}日`;
}

const formatDatetime = (yyyymmdd: number, hhmmss: number) => {
    const date = formatDate(yyyymmdd);
    const h = Math.floor(hhmmss / 10000);
    const s = Math.floor((hhmmss % 10000) / 100);
    return `${date} ${h > 9 ? h : '0' + h}:${s > 9 ? s : '0' + s}`;
}

const run = async (chatid: string, jobs: string[], year: string) => {
    const sumary = await Stat.Instance.sum(jobs, year);
    if (sumary.totalCnt == 0) {
        console.log('no sumary:', jobs.join(', '));
        return;
    }

    let callMost = '', failedMostUser = '', failedMostCnt = 0;
    const dateMap: { [yyyymmdd: number]: number } = {};
    for (const user in sumary.callerMap) {
        const arr = sumary.callerMap[user];
        if (!callMost || arr.length > sumary.callerMap[callMost].length) {
            callMost = user;
        }
        let failedCnt = 0;
        for (const b of arr) {
            if (!b.success) failedCnt++;
            dateMap[b.yyyymmdd] = (dateMap[b.yyyymmdd] || 0) + 1;
        }
        if (!failedMostUser || failedCnt > failedMostCnt) {
            failedMostUser = user;
            failedMostCnt = failedCnt;
        }
    }

    let buildMostDate = '', buildMostCnt = 0;
    for (const yymmdd in dateMap) {
        const cnt = dateMap[yymmdd];
        if (!buildMostDate || cnt > buildMostCnt) {
            buildMostDate = yymmdd;
            buildMostCnt = cnt;
        }
    }

    const totalCost = formatDuration(sumary.totalDuration, false);
    const latestDatetime = formatDatetime(sumary.latest.yyyymmdd, sumary.latest.hhmmss);
    const longestCost = formatDuration(sumary.longest.duration, true);
    const longestDatetime = formatDatetime(sumary.longest.yyyymmdd, sumary.longest.hhmmss);

    Postman.Instance.setChatId(chatid);
    await sendMsg(chatid, year, String(sumary.totalCnt), `这一年，你们总共执行了${sumary.totalCnt}次构建`, '不管怎么说，这都是真爱');
    await sendMsg(chatid, year, String(sumary.failedCnt), `这一年，一共遭遇了${sumary.failedCnt}次构建失败`, '失败了还一直点干嘛！');
    await sendMsg(chatid, year, totalCost, `这一年，一共花了这么多构建时间`, '我都不累，你好意思说累？');
    await sendMsg(chatid, year, formatDate(Number(buildMostDate)), `这一天，构了${buildMostCnt}次，把我都薅秃了`, '你们是不是心虚呢！');
    await sendMsg(chatid, year, latestDatetime, `这一天都发生了什么？`, '夜深人静的时候，希望你慎独！');
    await sendMsg(chatid, year, longestCost, `${longestDatetime}，这一次怎么构了这么久？`, sumary.longest.duration > 3600 ? '论持久，你比比？' : (sumary.longest.duration > 900 ? '还算正常啦' : '去看下医生吧'));
    await sendMsg(chatid, year, callMost, `这一年，${callMost}构了${sumary.callerMap[callMost].length}次，就你构得最多！`, '你老点我！');
    await sendMsg(chatid, year, failedMostUser, `这一年，你总共构了${sumary.callerMap[failedMostUser].length}次，失败了${failedMostCnt}次`, '你真黑啊！');
}

// testchatgroup
await run('projdpcq', ['斗破'], '2024');
await run('projyzzh', ['勇者之海', '暴走弹头'], '2024');
await run('projdpcqwx', ['三味书屋'], '2024');
